package com.gwz.shelf.config;

import com.gwz.shelf.entity.base.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.naming.AuthenticationException;
import java.util.List;

/**
 * @author lenovo
 */
@Slf4j
@RestControllerAdvice
public class MyExceptionHandler {



    @ExceptionHandler(value = BindException.class)
    @ResponseBody
    public Result methodArgumentNotValidExceptionHandler(BindException e) {
        log.error("参数绑定异常", e);
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        return Result.fail(getErrMsgByFieldError(fieldErrors));
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Result exceptionHandler(Exception e) {
        log.error("系统异常", e);
        return Result.fail(e.toString());

    }

    private String getErrMsgByFieldError(List<FieldError> fieldErrors) {
        String errFormat = "column: %s message: %s ";
        StringBuilder result = new StringBuilder();
        for (FieldError fieldError : fieldErrors) {
            result.append(String.format(errFormat, fieldError.getField(), fieldError.getDefaultMessage()));
        }
        return result.toString();
    }
}